package cn.toolck.my.spring.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

/**
 * @ClassName FileUtils
 * @Description TODO
 * @Author Toolck Rin
 * @Date 2021/2/9 12:32
 * @Version 1.0
 **/
public class FileUtils {
    public static List<Class> scanPackage(String[] basePackages) {
        List<Class> result = new ArrayList<>();
        for (String basePackage : basePackages) {
            String path = StringUtils.getPath(basePackage);
            try {
                result.addAll(FileUtils.getAllFile(path));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }



    public static List<Class> getAllFile(String path) throws Exception {
        Enumeration<URL> resourceUrls = FileUtils.class.getClassLoader().getResources(path);
        List<Class> result = new ArrayList<>();
        while (resourceUrls.hasMoreElements()) {
            URL url = resourceUrls.nextElement();
            if ("file".equals(url.getProtocol())) {
                String file = URLDecoder.decode(url.getFile(), "UTF-8");
                File dir = new File(file);
                result.addAll(parseClassFile(dir, path));
            }
        }
        return result;
    }

    private static List<Class> parseClassFile(File dir, String path) throws ClassNotFoundException {
        List<Class> result = new ArrayList<>();
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files == null) {
                return result;
            }
            for (File file : files) {
                result.addAll(parseClassFile(file, path));
            }
        } else if ((dir.getName().endsWith(".class"))) {
            String name = dir.getPath();
            name = name.substring(name.indexOf("classes") + 8).replace("\\", ".");
            name = name.substring(0, name.lastIndexOf("."));
            Class<?> aClass = Class.forName(name);
            result.add(aClass);
        }
        return result;
    }

}
